package com.pcbly.web.components.utils.fileupload;

import java.io.File;
import java.util.List;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import com.pcbly.web.components.utils.BeanUtils;
import com.pcbly.web.components.utils.ClassUtilsStatic;

//需要加上对Collection的处理
@SuppressWarnings("unchecked")
public class BeanUnSerializer {
	private Logger logger=Logger.getLogger(BeanUnSerializer.class);
	private BeanUtils bu=new BeanUtils();
	
	public Node readXMLFile(String filePath) throws DocumentException{
		logger.debug("装载xml");
		SAXReader reader=new SAXReader();
		Document rootDoc=reader.read(new File(filePath));
		Node actionNode=rootDoc.selectSingleNode("/ajax-request/action");
		return actionNode;
	}
	public Object loadAction(Node rootNode) throws ClassNotFoundException{
		return BeanUtils.newObject(
				ClassUtilsStatic.forName(
						((Element)rootNode).attribute("type").getText()));
	}
	
	private String formatBeanPropertyName(String propertyName){
		if (propertyName.length()>1){
			StringBuffer sb=new StringBuffer(propertyName.substring(0,1).toUpperCase());
			sb.append(propertyName.substring(1));
			return sb.toString();
		}
		else{
			return propertyName.toUpperCase();
		}
	} 
	public void loadBean(Node node,Object parentObject) throws SecurityException, NoSuchFieldException{
		List beanList=node.selectNodes("bean");
		//发现bean
		if (beanList.size()>0){
			//处理bean
			logger.debug("发现bean，开始逐一处理");
			for(int i=0;i<beanList.size();i++){
				Element ele=(Element)beanList.get(i);
				//获得bean对象
				Class beanClazz=parentObject.getClass().getDeclaredField(ele.attribute("name").getText()).getType();
				logger.debug("获取bean类型:"+beanClazz);
				Object beanObj=BeanUtils.newObject(beanClazz);
				Class[] paramTypes=new Class[1];
				Object[] paramValues=new Object[1];
				paramTypes[0]=beanClazz;
				paramValues[0]=beanObj;
				//set bean
				bu.callMethod(parentObject, "set"+formatBeanPropertyName(ele.attribute("name").getText()), paramTypes, paramValues);
				loadBean(ele,beanObj);
			}
		}
		List propertyList=node.selectNodes("property");
		for(int i=0;i<propertyList.size();i++){
			Element ele=(Element)propertyList.get(i);
			bu.setBeanFieldValue(parentObject,ele.attribute("name").getText(), ele.getText());
		}
	}
}
